package com.company.nuwa.redis;

import cn.hutool.core.util.ObjectUtil;
import com.company.nuwa.redis.support.limit.RedisRateLimiter;
import com.company.nuwa.redis.support.limit.RedisRateLimiterAspect;
import com.company.nuwa.redis.support.lock.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Objects;

/**
 * <p>redisson client</p >
 *
 * @author Nikola Tesla
 * @version 1.0
 * @date 2021/03/02 14:00
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonClientConfiguration {

    @Bean
    public RedisRateLimiterAspect customRedisRateLimiterAspect(RedisRateLimiter customRedisRateLimiter) {
        return new RedisRateLimiterAspect(customRedisRateLimiter);
    }

    @Bean
    public RedisRateLimiter customRedisRateLimiter(RedissonClient redissonClient) {
        return new RedisRateLimiter(redissonClient);
    }

    @Bean
    public RedisLockerAspect customRedisLockAspect(RedisLocker customRedisLocker) {
        return new RedisLockerAspect(customRedisLocker);
    }

    @Bean
    @ConditionalOnMissingBean
    public LockKeyBuilder lockKeyBuilder() {
        return new DefaultLockKeyBuilder();
    }

    @Bean
    @ConditionalOnMissingBean
    public LockFailureStrategy lockFailureStrategy() {
        return new DefaultLockFailureStrategy();
    }

    @Bean
    public RedisLocker customRedisLocker(RedissonClient redissonClient, LockKeyBuilder lockKeyBuilder, LockFailureStrategy lockFailureStrategy) {
        return new RedisLocker(redissonClient, lockKeyBuilder, lockFailureStrategy);
    }

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redissonClient) {
        Logger.log.info("======> redisson connection factory init <======");
        return new RedissonConnectionFactory(redissonClient);
    }

    @SneakyThrows
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = initRedissonConfig(redisProperties);
        Logger.log.info("======> redisson client init <====== \n {}", config.toYAML());
        return Redisson.create(config);
    }

    /**
     * 初始化 redisson 配置
     * 此处用 {@link RedisProperties} 是为了参照spring约定去集成，方便切换其它redis客户端
     * <p>
     * 优先按照集群模式去解析配置
     * <p>
     * 然后按照哨兵模式去解析配置
     * <p>
     * 最后按照单点模式去解析配置
     *
     * @param properties
     * @return
     */
    private Config initRedissonConfig(RedisProperties properties) {
        Duration timeout = ObjectUtil.defaultIfNull(properties.getTimeout(), Duration.ofMillis(3000));

        Config config = new Config();

        // cluster servers
        RedisProperties.Cluster cluster = properties.getCluster();

        // Password for Redis authentication. Should be null if not needed
        // 避免通过yaml配置了控字符串
        String password = StringUtils.isBlank(properties.getPassword()) ? null : properties.getPassword();
        if (Objects.nonNull(cluster)) {
            String[] nodeAddress = cluster.getNodes().stream()
                    .map(address -> "redis://" + address)
                    .toArray(String[]::new);
            config.useClusterServers()
                    .addNodeAddress(nodeAddress)
                    .setPassword(password)
                    .setTimeout((int) timeout.toMillis());
            return config;
        }

        // sentinel servers
        RedisProperties.Sentinel sentinel = properties.getSentinel();
        if (Objects.nonNull(sentinel)) {
            String[] sentinelAddresses = sentinel.getNodes().stream()
                    .map(address -> "redis://" + address)
                    .toArray(String[]::new);
            config.useSentinelServers()
                    .setMasterName(sentinel.getMaster())
                    .addSentinelAddress(sentinelAddresses)
                    .setDatabase(properties.getDatabase())
                    .setPassword(password)
                    .setTimeout((int) timeout.toMillis());
            return config;
        }

        // single server
        config.useSingleServer()
                .setAddress("redis://" + properties.getHost() + ":" + properties.getPort())
                .setDatabase(properties.getDatabase())
                .setPassword(password)
                .setTimeout((int) timeout.toMillis());

        return config;
    }

    @Slf4j
    static class Logger {
    }

}
